<template>
  <div class="hdr-container" :style="{ width: '240px' }">
    <!-- 缩略图区域 -->
    <div class="tag">天空盒子</div>
    <div class="thumbnail-wrapper" @click="openFileDialog" :class="{
      'has-image': hdrDataUrl,
      'highlight': highlight,
      'outline': outline
    }">
      <!-- 实际HDR缩略图 -->
      <img v-if="thumbnailUrl" :src="thumbnailUrl" alt="HDR缩略图" class="hdr-thumbnail" />

      <div v-else class="upload-placeholder">
        <span>点击上传HDR全景图</span>
        <div class="format-hint">仅支持 .hdr 格式</div>
      </div>

      <input type="file" ref="fileInput" @change="handleHdrUpload" accept=".hdr" style="display: none" />
    </div>

    <!-- 上传进度条 -->
    <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
      <div class="progress-bar" :style="{ width: uploadProgress + '%' }"></div>
      <div class="progress-text">{{ uploadProgress }}%</div>
    </div>
    <div ref="canvasContainer" style="display: none"></div>
    <hr>
    <!-- 属性开关区域 -->
    <div class="property-controls">
      <div class="property-item">
        <label>
          <input type="checkbox" v-model="visibleAxesHelper" />
          显示坐标轴
        </label>
      </div>
      <div class="property-item">
        <label>
          <input type="checkbox" v-model="highlight" />
          显示光源helper
        </label>
      </div>
      <div class="property-item">
        <label>
          <input type="checkbox" v-model="outline" />
          显示网格
        </label>
      </div>
    </div>

    <hr>
    <div class="tag">地图</div>
    <el-select v-model="form.type" placeholder="请选择天气" size="small" placement="bottom" class="me-select"
      @change="changeMap">
      <el-option label="无" value="null" />
      <el-option label="tif->png" value="tif" />
      <el-option label="天地图瓦片" value="tile" />
    </el-select>

    <div class="thumbnail-wrapper" @click="mapDialog" :class="{
      'has-image': hdrDataUrl,
      'highlight': highlight,
      'outline': outline
    }">
      <!-- 实际HDR缩略图 -->
      <img v-if="mapUrl" :src="mapUrl" alt="地图缩略图" class="hdr-thumbnail" />

      <div v-else class="upload-placeholder">
        <span>点击上传tif转的png</span>
        <div class="format-hint">仅支持 .png 格式</div>
      </div>

      <input type="file" ref="mapInput" @change="uploadMap" accept=".png" style="display: none" />
    </div>

    <el-input class="range"  size="small" placeholder="Please input">
      <template #prepend>MaxLon</template>
    </el-input>
    <el-input class="range" size="small" placeholder="Please input">
      <template #prepend>MinLon</template>
    </el-input>
    <el-input class="range"  size="small" placeholder="Please input">
      <template #prepend>MaxLat</template>
    </el-input>
    <el-input class="range" size="small" placeholder="Please input">
      <template #prepend>MinLat</template>
    </el-input>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive, watchEffect } from 'vue';
import * as THREE from 'three'; // 使用Three.js处理HDR文件
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js'

const fileInput = ref(null);
const hdrDataUrl = ref('');
const thumbnailUrl = ref('');
const fileName = ref('');
const uploadProgress = ref(0);
const imageInfo = ref({
  resolution: '',
  size: 0
});

const form = reactive({
  type: 'null',
  size: 1,
  speed: 10,
  height: 500,
  area: 1000,
  number: 1000
})

// 属性开关
const visibleAxesHelper = ref(false);
const highlight = ref(true);
const outline = ref(false);
const axesHelper = new THREE.AxesHelper(50);


//显隐helper
watch(highlight, (newValue, oldValue) => {
  meteor3D.Light.visibleHelper(newValue)
});

//显隐坐标轴
watch(visibleAxesHelper, (newValue, oldValue) => {
  if (newValue) {
    meteor3D.scene.add(axesHelper);
  } else {
    meteor3D.scene.remove(axesHelper);
  }
})

const openFileDialog = () => {
  fileInput.value.click();
};

onMounted(() => {
  createHdrUrl('./assets/day.hdr')
})
const handleHdrUpload = async (event) => {
  const file = event.target.files[0];
  if (file) {
    if (!file.name.toLowerCase().endsWith('.hdr')) {
      alert('请上传.hdr格式的文件');
      return;
    }

    fileName.value = file.name;
    imageInfo.value.size = file.size;

    // 上传进度
    uploadProgress.value = 0;
    const progressInterval = setInterval(() => {
      uploadProgress.value += 10;
      if (uploadProgress.value >= 100) {
        clearInterval(progressInterval);
        const blobUrl = URL.createObjectURL(file)
        createHdrUrl(blobUrl);
      }
    }, 100);
  }
};


const canvasContainer = ref()
let renderer = null


const createHdrUrl = async (url) => {

  // 用 URL.createObjectURL 生成 Blob URL，配合 RGBELoader.loadAsync 使用
  const blobUrl = url
  // 设置 renderer
  renderer = new THREE.WebGLRenderer({ preserveDrawingBuffer: true })
  renderer.setSize(256, 256)
  renderer.outputEncoding = THREE.sRGBEncoding
  renderer.toneMapping = THREE.ACESFilmicToneMapping
  renderer.toneMappingExposure = 1.0
  canvasContainer.value.innerHTML = ''
  canvasContainer.value.appendChild(renderer.domElement)

  // 加载 HDR 贴图
  const loader = new RGBELoader()
  const hdrTexture = await loader.loadAsync(blobUrl)
  hdrTexture.mapping = THREE.EquirectangularReflectionMapping

  const pmremGen = new THREE.PMREMGenerator(renderer)
  pmremGen.compileEquirectangularShader()

  const envMap = pmremGen.fromEquirectangular(hdrTexture).texture

  // 创建场景
  const scene = new THREE.Scene()
  scene.background = envMap

  // 创建球体反射贴图用于显示效果
  const geometry = new THREE.SphereGeometry(0.4, 64, 64)
  const material = new THREE.MeshStandardMaterial({
    envMap,
    metalness: 1,
    roughness: 0,
  })
  const mesh = new THREE.Mesh(geometry, material)
  scene.add(mesh)

  const camera = new THREE.PerspectiveCamera(70, 1, 0.1, 10)
  camera.position.z = 1

  const light = new THREE.AmbientLight(0xffffff, 1)
  scene.add(light)

  renderer.render(scene, camera)

  thumbnailUrl.value = renderer.domElement.toDataURL('image/png')

  meteor3D.loadHrd(blobUrl)

  // 释放资源
  URL.revokeObjectURL(blobUrl)
  hdrTexture.dispose()
  pmremGen.dispose()
  envMap.dispose()
  material.dispose()
  geometry.dispose()
}

const mapUrl = ref('')
const mapInput = ref(null);
const mapDialog = () => {
  mapInput.value.click();
};
const uploadMap = async (event) => {
  const file = event.target.files[0];
  if (file) {
    if (!file.name.toLowerCase().endsWith('.png')) {
      alert('请上传.png格式的文件');
      return;
    }

    fileName.value = file.name;
    imageInfo.value.size = file.size;


    const blobUrl = URL.createObjectURL(file)
    mapUrl.value = blobUrl
  }
}

const changeMap = (val) => {
  switch (val) {
    case 'null':

      meteor3D.Map.remove()
      break;

    case 'tif':
      meteor3D.Map.add()
      break;
    default:
      break;
  }
}

</script>

<style scoped>
.range {
  margin: 5px 0;
}

.tag {
  display: inline-block;
  padding: 1px 4px;
  font-size: 11px;
  color: #333;
  background-color: #e0f4ff;
  border-radius: 16px;
  border: 1px solid #b3e0ff;
  font-family: Arial, sans-serif;
  cursor: default;
  transition: background-color 0.3s, color 0.3s;
  margin: 8px 0;
}

hr {
  margin: 5px 0;
  border-color: black;
}

.hdr-container {
  font-family: Arial, sans-serif;
  /* border: 1px solid #ddd; */
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* background-color: #1a1a1a; */
  color: #e0e0e0;
}

.thumbnail-wrapper {
  width: 100%;
  height: 160px;
  background-color: #2a2a2a;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease;
  border: 1px dashed #444;
  margin: 8px 0;
}

.thumbnail-wrapper.has-image {
  border-color: #666;
  background-color: #1e1e1e;
}

.thumbnail-wrapper.highlight {
  box-shadow: 0 0 15px rgba(76, 175, 80, 0.5);
}

.thumbnail-wrapper.outline {
  border: 2px solid #4CAF50;
}

.thumbnail-wrapper:hover {
  border-color: #4CAF50;
}

.hdr-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hdr-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.hdr-icon {
  font-size: 14px;
  font-weight: bold;
  color: #4CAF50;
  background: rgba(76, 175, 80, 0.1);
  padding: 4px 8px;
  border-radius: 12px;
  margin-bottom: 6px;
}

.hdr-info {
  text-align: center;
}

.hdr-filename {
  font-size: 11px;
  color: white;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.hdr-resolution {
  font-size: 10px;
  color: #ccc;
}

.upload-placeholder {
  color: #999;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.format-hint {
  font-size: 11px;
  margin-top: 8px;
  color: #666;
}

.property-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding-top: 10px;
}

.property-item {
  display: flex;
  align-items: center;
}

.property-item label {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-size: 14px;
}

/* 上传进度条 */
.upload-progress {
  width: 100%;
  height: 20px;
  background-color: #333;
  border-radius: 10px;
  margin-top: 10px;
  overflow: hidden;
  position: relative;
}

.progress-bar {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  color: white;
}
</style>